package com.vincce.sport.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.vincce.sport.core.utils.CheckUtil;
import com.vincce.sport.core.utils.SimpleStorageClient;
import com.vincce.sport.entity.ImgModel;
import com.vincce.sport.entity.ImgStorage;
import com.vincce.sport.entity.ImgTemp;
import com.vincce.sport.entity.Page;
import com.vincce.sport.mapper.ImgModelMapper;
import com.vincce.sport.mapper.ImgStorageMapper;
import com.vincce.sport.mapper.ImgTempMapper;


@Controller
@RequestMapping("/imgModel")
public class ImgModelController extends BaseController{
	@Resource
	private ImgModelMapper imgModelMapper;
	@Resource
	private ImgTempMapper imgTempMapper;
	@Resource
	private ImgStorageMapper imgStorageMapper;

    @RequestMapping("/list")
    public String ImgModelList(Model model, ImgModel imgModel, Page<ImgModel> page) throws IOException{
        Map<String, Object> filter = new HashMap<String, Object>();
        if(imgModel.getName() != null && !imgModel.getName().equals("")){
            filter.put("name", imgModel.getName());
        }
		if(imgModel.getStatus() != null && !imgModel.getStatus().equals("")){
			filter.put("status", imgModel.getStatus());
		}
        page.setFilter(filter);

        page.setResult(imgModelMapper.queryImgModelList(page));
        page.setTotal(imgModelMapper.queryImgModelCount(page.getFilter()));
        model.addAttribute("page",page);
        
        
        List<ImgTemp> imgTempList = imgTempMapper.findAllImgTemp();
        model.addAttribute("imgTempList",imgTempList);
        
        return "backstage/imgModelList";
    }

    @RequestMapping("/addOrUpdate")
    @ResponseBody
    public String addOrUpdateImgModel(Model model, ImgModel imgModel, HttpServletRequest request) throws IOException{
        Long count = 0l;
        if(CheckUtil.isEmpty(imgModel.getId())){
        	imgModel.setCreateTime(new Date());
        	imgModel.setCreateUser(getCurrentUser().getId());
        	count = imgModelMapper.insertImgModel(imgModel);
        } else{
        	count = imgModelMapper.updateImgModel(imgModel);
        }

        Map<String, Object> result = new HashMap<String, Object>();
        result.put("suc", count > 0 ? true : false);
        return JSON.toJSONString(result);
    }

    @RequestMapping("/delete")
    @ResponseBody
    public String deleteImgModel(Model model, Long id, HttpServletRequest request) throws IOException{
        Boolean flag = false;

        imgModelMapper.deleteById(id);

        flag = true;
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("obj", flag);
        return JSON.toJSONString(result);
    }

    /**
     * 檢查模块名是否已存在
     * @param resourceName
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("/checkImgModelName")
    @ResponseBody
    public String checkImgModelName(String name,Long id) throws Exception{
        ImgModel imgModel =new ImgModel();
        if(name != null && !name.equals("")){
        	imgModel.setName(name);
        }
        if(id!= null && !id.equals("")){
        	imgModel.setId(id);
        }
        Integer fg = 0;
        List<ImgModel> imgModelList = imgModelMapper.findImgModelByOne(imgModel);
        if(imgModelList!=null && imgModelList.size()>0){
        	fg = 1;
        }
        return Boolean.toString(fg==0);
    }
    
    /*********************************************************前台页面分割线*******************************************************************/
    public static String SRC = "demo_src_";
	public static String TIME = "demo_time_";
	public static String NUM = "demo_num_";
	
    @RequestMapping("/pictureList")
    public String pictureList(Model model, HttpServletRequest request){
    	List<ImgModel> imgModelList = imgModelMapper.findAllImgModel();	
//    	if(imgModelList !=null && imgModelList.size()>0){
//    		for(int i=0;i<imgModelList.size();i++){
//    			if(i==2){
//    				break;
//    			}
//    			imgModelList.set(i, replaceContent(imgModelList.get(i)));
//    		}
//    	}
    	model.addAttribute("imgModelList", imgModelList);
    	return "foreground/picture";
    }
    
    @RequestMapping("/getModelPic")
    @ResponseBody
    public String getModelPic(Model model, Long id, HttpServletRequest request) throws IOException{
        Boolean flag = false;
        ImgModel imgModel = imgModelMapper.findImgModelById(id);
        String content = replaceContent(imgModel);
        flag = true;
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("obj", flag);
        if(content !=null && !content.equals("")){
        	result.put("content", content);
        } else{
        	result.put("content", "<div class='pic-no'>尽请期待！</div>");
        }
        
        return JSON.toJSONString(result);
    }
    
    /**
     * 查找模块对应的内容
     * @param imgModel
     * @return
     */
    public String replaceContent(ImgModel imgModel){
    	ImgTemp imgTemp = imgTempMapper.findImgTempById(imgModel.getTempId());
    	if(imgTemp != null){
    		String content = imgTemp.getContent();
    		ImgStorage imgStorage = new ImgStorage();
    		imgStorage.setModelId(imgModel.getId());
    		imgStorage.setTempId(imgModel.getTempId());
    		List<ImgStorage> imgStorageList = imgStorageMapper.findImgStorageByOne(imgStorage);
    		if(imgStorageList!=null && imgStorageList.size()>0){
    			for(int i=1;i<=imgStorageList.size();i++){
    				if(imgStorageList.get(i-1).getImgPath() != null) {
    					content = content.replace(SRC + i, String.format(SimpleStorageClient.REQUEST_URI2_PREFIX + imgStorageList.get(i-1).getImgPath(),"ori"));
    				}
    				if(imgStorageList.get(i-1).getCreateTime() != null){
    					SimpleDateFormat sdf2=new SimpleDateFormat("yyyy年MM月dd日");
    					content = content.replace(TIME+i, sdf2.format(imgStorageList.get(i-1).getCreateTime())+"上传");
    				}
    				if(imgStorageList.get(i-1).getClickNum() != null){
    					content = content.replace(NUM+i, "总点击人数"+imgStorageList.get(i-1).getClickNum()+"人");
    				}
    			}
    		}
    		imgModel.setContent(content);
    	}
		return imgModel.getContent();
    }
    
    @RequestMapping("/pictureDetail")
    public String pictureDetail(Model model, Long id, HttpServletRequest request){
    	if(id != null  && !id.equals("")){
    		ImgModel imgModel = imgModelMapper.findImgModelById(id);
    		ImgStorage imgStorage = new ImgStorage();
    		imgStorage.setModelId(id);
    		imgStorage.setTempId(imgModel.getTempId());
    		List<ImgStorage> imgStorageList = imgStorageMapper.findImgStorageByOne(imgStorage);
    		for(ImgStorage isl:imgStorageList){
				if(isl.getImgPath() != null) {
					isl.setImgPath(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX + isl.getImgPath(),"ori"));
				}
			}
    		model.addAttribute("imgStorageList", imgStorageList);
    		model.addAttribute("imgModel", imgModel);
        	return "foreground/picture-detail";
    	} else{
    		return pictureList(model, request);
    	}
		
    }
}
